from flask import Flask, request, jsonify
import requests
import os

app = Flask(__name__)

# 配置Java API地址（示例，实际应从环境变量获取）
JAVA_API_URL = os.getenv('JAVA_API_URL', 'http://java-api.example.com/data')


class PetImageData:
    """宠物图像数据对象"""

    def __init__(self, user_id: int, pet_id: int, image_base64: str):
        self.user_id = user_id
        self.pet_id = pet_id
        self.image_base64 = image_base64

    def __str__(self):
        return f"PetImageData(user_id={self.user_id}, pet_id={self.pet_id}, image_size={len(self.image_base64)} bytes)"


class JavaAPIAdapter:
    """Java API适配器"""

    @staticmethod
    def fetch_data(user_id: int, pet_id: int, image_base64: str) -> PetImageData:
        """从Java接口获取数据"""
        try:
            response = requests.get(
                f"{JAVA_API_URL}/{user_id}/{pet_id}/{image_base64}",
                timeout=5
            )

            if response.status_code == 200:
                data = response.json()
                return PetImageData(
                    user_id=data['userId'],
                    pet_id=data['petId'],
                    image_base64=data['imageData']
                )
            elif response.status_code == 404:
                raise ValueError("Requested data not found")
            else:
                raise ConnectionError(f"Unexpected API response: {response.status_code}")

        except requests.exceptions.RequestException as e:
            raise ConnectionError(f"API connection failed: {str(e)}")


@app.route('/process', methods=['POST'])
def handle_request():
    """处理请求的主入口"""
    try:
        # 验证输入参数
        request_data = request.get_json()
        if not request_data:
            return jsonify({"status": 400, "message": "Empty request body"}), 400

        user_id = int(request_data.get('user_id', 0))
        pet_id = int(request_data.get('pet_id', 0))

        if user_id <= 0 or pet_id <= 0:
            return jsonify({"status": 400, "message": "Invalid user_id or pet_id"}), 400

        # 从Java API获取数据
        pet_data = JavaAPIAdapter.fetch_data(user_id, pet_id)

        # 执行业务处理（由用户实现）
        processed_data = your_business_logic(pet_data)  # 这里替换为用户的业务逻辑

        # 返回处理结果
        return jsonify({
            "status": 200,
            "message": "Success",
            "data": str(processed_data)
        }), 200

    except ValueError as e:
        return jsonify({"status": 404, "message": str(e)}), 404
    except ConnectionError as e:
        return jsonify({"status": 502, "message": str(e)}), 502
    except Exception as e:
        app.logger.error(f"Unexpected error: {str(e)}")
        return jsonify({"status": 500, "message": "Internal server error"}), 500


def your_business_logic(pet_data: PetImageData) -> PetImageData:
    """业务处理函数（由用户实现）"""
    # 示例处理：添加处理逻辑
    # 这里可以添加具体的业务处理代码
    return pet_data


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)